package com.bestv.bsr.cloud.common;

import com.bestv.bsr.core.annotations.OptionalComponent;
import com.bestv.bsr.core.properties.AHRecommendProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author taojiacheng
 */
@Slf4j
@RequiredArgsConstructor
@OptionalComponent(value = "bsrThreadFactory", strategy = OptionalComponent.Strategy.CLOUD)
public class BsrThreadFactory {

    private final AHRecommendProperties properties;
    private ExecutorService executorService;


    @PostConstruct
    public void init() {
        log.info("init bsrThreadFactory");
        AHRecommendProperties.ThreadPoolProperties threadPool = properties.getThreadPool();
        executorService = new ThreadPoolExecutor(threadPool.getCorePoolSize(),
                threadPool.getMaxPoolSize(),
                threadPool.getKeepAlive(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(threadPool.getQueueSize()),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("bsr-thread-" + thread.getId());
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    public void execute(Runnable runnable) {
        executorService.execute(runnable);
    }


    @PreDestroy
    public void shutdown() {
        log.info("shutdown bsrThreadFactory");
        executorService.shutdown();
    }


}
